package com.leonzhangxf.code.api;

import com.leonzhangxf.code.domain.AuthCode;
import com.leonzhangxf.code.repository.AuthCodeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDateTime;
import java.util.concurrent.ThreadLocalRandom;

/**
 * @author leonzhangxf
 */
@RestController
@RequestMapping("/code")
public class CodeApi {

    private AuthCodeRepository authCodeRepository;

    private EmailApi emailApi;

    @GetMapping("/create/{email}")
    @Transactional(rollbackFor = Exception.class)
    public Boolean create(@PathVariable("email") String email) {
        String code = String.format("%d", getCode());

        AuthCode authCode = new AuthCode();
        authCode.setCode(code);
        authCode.setEmail(email);
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime expireTime = now.plusMinutes(10);
        authCode.setCreateTime(now);
        authCode.setExpireTime(expireTime);
        authCodeRepository.save(authCode);
        return emailApi.sendEmail(email, code);
    }

    private int getCode() {
        return ThreadLocalRandom.current().nextInt(100000, 1000000);
    }

    /**
     *
     * @return 校验验证码是否正确，0正确1错误2超时
     */
    @GetMapping("/validate/{email}/{code}")
    public Integer validate(
        @PathVariable("email") String email,
        @PathVariable("code") String code
    ) {
        AuthCode authCode = authCodeRepository.findByEmailOrderByCreateTimeDesc(email).get(0);
        LocalDateTime now = LocalDateTime.now();
        if (now.isAfter(authCode.getExpireTime())) {
            return 2;
        }
        if (!authCode.getCode().equals(code)) {
            return 1;
        }
        return 0;
    }

    @Autowired
    public void setEmailApi(EmailApi emailApi) {
        this.emailApi = emailApi;
    }

    @Autowired
    public void setAuthCodeRepository(AuthCodeRepository authCodeRepository) {
        this.authCodeRepository = authCodeRepository;
    }
}
